package server

import (
	"context"
	"fmt"
	global2 "longmen/server/config/global"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_live"
	db_main2 "longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"longmen/server/pkg/protobuf"
	"time"
)

func (s *Server) LiveStore(ctx context.Context, r *protobuf.LiveStoreReq) (*protobuf.LiveStoreResp, error) {
	res, total, err := db_live.LiveStore(int(r.Page), int(r.Size))
	return &protobuf.LiveStoreResp{
		Total:     total,
		LiveStore: res,
	}, err
}

func (s *Server) LiveStoreOrder(ctx context.Context, r *protobuf.LiveStoreOrderReq) (*protobuf.LiveStoreOrderResp, error) {
	user, _ := s.GetUserInfo(ctx, &protobuf.GetUserInfoReq{Uid: uint64(r.GetUid())})
	status, err := liveStoreOrder(r.GetId(), r.GetUid(), r.GetPayType(), user)
	if err != nil {
		return &protobuf.LiveStoreOrderResp{
			Status: int32(status),
		}, err
	}
	cache.DelUserFullCache(int(r.GetUid()))
	return &protobuf.LiveStoreOrderResp{
		Status: int32(status),
	}, err
}

func (s *Server) LiveStoreOrderList(ctx context.Context, r *protobuf.LiveStoreOrderListReq) (*protobuf.LiveStoreOrderListResp, error) {
	res, total, err := db_live.LiveStoreOrderList(int(r.Uid), int(r.Page), int(r.Size))
	return &protobuf.LiveStoreOrderListResp{
		Total:              total,
		LiveStoreOrderList: res,
	}, err
}

func liveStoreOrder(id int64, uid int64, payType int32, user *protobuf.GetUserInfoResp) (int, error) {
	var (
		err              error
		status           int = 1
		in               int
		inType           _const.FundsType
		payDiamondAmount int = 0
		payGoldAmount    int = 0
		store            *protobuf.LiveStore
		deliveryStatus   int32 = 0
	)

	if payType != 1 && payType != 2 {
		status = 4
		if err != nil {
			return status, err
		}
	}

	err = global2.Live().Table("db_live_store").Where("id=?", id).Limit(1).Find(&store).Error

	if err != nil {
		status = 2
		return status, err
	}

	if payType == 1 {
		in = int(store.Diamond)
		inType = _const.CoinDiamond
		payDiamondAmount = in
	}

	if payType == 2 {
		in = int(store.Gold)
		inType = _const.CoinGold
		payGoldAmount = in
	}

	if user.NobleId > 0 && store.VipDiscount == 1 && user.GiftDiscount > 0 {
		in = in * int(user.GiftDiscount) / 100

		if payType == 1 {
			payDiamondAmount = in
		}
		if payType == 2 {
			payGoldAmount = in
		}
	}

	if store.Type == 1 {
		deliveryStatus = 1
	}

	if payType == 1 && store.Diamond <= 0 {
		status = 4
		return status, err
	}

	if payType == 2 && store.Gold <= 0 {
		status = 4
		return status, err
	}

	if payType == 1 && int(user.Diamond) < int(payDiamondAmount) {
		status = 3
		return status, err
	}

	if payType == 2 && int(user.Gold) < int(payGoldAmount) {
		status = 3
		return status, err
	}

	// 写订单
	r := &protobuf.LiveStoreOrderList{
		Uid:         uid,
		Type:        store.Type,
		PayType:     payType,
		OrderNo:     util.CreateOrderNo(int(uid), "LS"),
		StoreId:     store.Id,
		PropsId:     store.PropsId,
		Diamond:     int64(payDiamondAmount),
		Gold:        int64(payGoldAmount),
		VipDiscount: store.VipDiscount,
		NobleId:     int32(user.NobleId),
		Thumb:       store.Thumb,
		Title:       store.Title,
		CreatedAt:   time.Now().Unix(),
		Status:      deliveryStatus,
	}
	tx := global2.Live().Begin()
	err = tx.Table("db_live_store_order").Create(&r).Error
	if err != nil {
		tx.Rollback()
		status = 2
		return status, err
	}

	// 扣钱
	profitLog := []*models_main.UserProfit{
		{
			Uid:         int(uid), //获得人的id, 这里是领取人
			CoinCount:   -int(in), //鹰钻或金坷拉数量
			FUid:        0,        //赠送人的ID, 系统赠送
			ConsumeType: _const.LIVE_STORE_ORDER,
			Type:        _const.TYPE_CONSUME,
			Content: fmt.Sprintf("%d 商城购物:%d",
				uid,
				r.Diamond,
			),
			Resid:      0,
			Count:      0,
			CreateTime: time.Now(),
			CoinType:   int(inType), //1-鹰钻 2-金坷拉
			OrderNo:    util.GenOrderId("RV", 1),
			Liveid:     0,
		},
	}
	userTx := global2.GetX().Begin()
	if err = db_main2.InsertUserProfitByTransactions(userTx, profitLog); err != nil {
		tx.Rollback()
		userTx.Rollback()
		global2.Log.Error("%s商城购物记录写入失败:%v", "LiveStoreOrder", profitLog)
	}

	_, _, err = db_main2.UpdateAmount(int(uid), -int(in), inType, _const.LIVE_STORE_ORDER)
	if err != nil {
		tx.Rollback()
		userTx.Rollback()
		status = 2
		return status, err
	}

	// 虚拟发货到背包
	if store.Type == 1 {
		//道具
		if store.PropsId > 0 {
			props, err := db_main2.GetPropsINFO(int(store.PropsId))
			if err != nil {
				tx.Rollback()
				userTx.Rollback()
				status = 2
				return status, err
			}
			err = db_main2.SaveUserItem(userTx, int(user.NobleId), int(uid), int(props.Id), props.Type, 1, props.Name, props.Remark, 3000*24*60*60)
			if err != nil {
				tx.Rollback()
				userTx.Rollback()
				status = 2
				return status, err
			}
		}

		if store.GiftId > 0 {
			gift, err := db_main2.GetGiftParam(map[string]interface{}{"id": store.GiftId})

			if err != nil {
				tx.Rollback()
				userTx.Rollback()
				status = 2
				return status, err
			}

			err = db_main2.SaveUserItem(userTx, int(user.NobleId), int(uid), int(gift.Id), gift.Type, 1, gift.Title, gift.Title, 3000*24*60*60)
			if err != nil {
				tx.Rollback()
				userTx.Rollback()
				status = 2
				return status, err
			}
		}
	}

	tx.Commit()
	userTx.Commit()

	return status, err
}
